package services

import (
	"context"
	"encoding/json"
	"fmt"
	"net/url"
	"strings"

	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/models"
)

// GetCardBin 查询卡bin信息
func GetCardBin(ctx context.Context, client *photonpay.PhotonPayClient, params models.CardBinQueryParams) (*models.CardBinResponse, error) {
	// 构建查询参数
	query := url.Values{}
	if params.CardFormFactor != "" {
		query.Set("cardFormFactor", params.CardFormFactor)
	}
	if params.CardType != "" {
		query.Set("cardType", params.CardType)
	}
	if params.CardScheme != "" {
		query.Set("cardScheme", params.CardScheme)
	}
	if params.CardCurrency != "" {
		query.Set("cardCurrency", params.CardCurrency)
	}

	// 构建请求路径
	path := "/vcc/openApi/v4/getCardBin"
	if len(query) > 0 {
		path += "?" + query.Encode()
	}

	// 发送请求
	resp, err := client.Get(ctx, path)
	if err != nil {
		return nil, fmt.Errorf("get card bin failed: %v", err)
	}

	// 解析响应
	var result models.CardBinResponse
	if err := json.Unmarshal(resp, &result); err != nil {
		return nil, fmt.Errorf("unmarshal response failed: %v", err)
	}

	// 检查响应状态
	if !result.IsSuccess() {
		return nil, &result
	}

	// 标准化响应格式
	standardizeCardBinResponse(&result)

	return &result, nil
}

// standardizeCardBinResponse 标准化卡BIN响应格式
// 将响应格式标准化为：code使用"0000"，布尔字段使用"Y"/"F"，卡组织使用大写
func standardizeCardBinResponse(response *models.CardBinResponse) {
	// 确保成功码为"0000"
	if response.Code == "200" {
		response.Code = "0000"
	}

	// 标准化每个卡BIN信息
	for i := range response.Data {
		bin := &response.Data[i]

		// 标准化布尔字段
		if strings.ToLower(bin.BillingAddressUpdatable) == "true" {
			bin.BillingAddressUpdatable = "Y"
		} else {
			bin.BillingAddressUpdatable = "F"
		}

		if strings.ToLower(bin.ExpiryDateCustomization) == "true" {
			bin.ExpiryDateCustomization = "Y"
		} else {
			bin.ExpiryDateCustomization = "F"
		}

		// 标准化卡组织为大写
		bin.CardScheme = strings.ToUpper(bin.CardScheme)
	}
}
